package com.itqn.servlet;

import com.alibaba.fastjson.JSONArray;
import com.itqn.util.AliOSSUtils;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;

@WebServlet(value = "/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    AliOSSUtils aliOSSUtils = new AliOSSUtils();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        try {
            // 解析请求的内容提取文件数据
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) { // 这是一个文件
                    String fileName = new File(item.getName()).getName(); // 获取上传文件的文件名
                    String filePath = "tmp/" + fileName; // 指定文件上传后的存储路径
                    File storeFile = new File(filePath);
                    // 保存文件到指定位置
                    item.write(storeFile);
                    String path = aliOSSUtils.upload(storeFile);
                    response.getWriter().write(path);
                    storeFile.delete();
                }
            }
        } catch (Exception e) {
            response.getWriter().write("文件上传失败!");
        }
    }

}
